﻿using System;
using Sunny.UI;
using System.Windows.Forms;
using System.IO;

namespace Easily._02_Form._01_frmCtrlConfig
{
    //[2021/03/08] 优化printf 推翻重做
    public partial class frmPrintf : Form
    {
        private GeneralIcon MyIcon = null;  //保存传入的控件对象 
        //以下三个参数都应该在对应控件的事件中赋值
        //首先获取printf提示语句：变量前字符串+变量后字符串
        string printf_tip_before = "";
        string printf_tip_after = "";
        //其次获取输出格式
        string printf_form = "";
        //然后获取要输出的变量数据
        string printf_data = "";

        /// <summary>
        /// 构造函数
        ///主要功能：加载保存的控件设置；生成初始代码；
        /// </summary>
        /// <param name="icon"></param>
        public frmPrintf(GeneralIcon icon)
        {
            InitializeComponent();
            this.MyIcon = icon;
            //comBox_Var.Items.Clear();//先清空之前存储的传感器变量名
            SetVariables();//设置comBox_Var的items
            //comBox_Var.Items.Add("");
            //Globaldefine.FrmParent.ActivedrmGraphicFlow != null && 
            if (MyIcon.code.Save != "")
            {
                //保存的参数共有5项，以英文分号';'分开            
                string[] tmp = MyIcon.code.Save.Split(';');
                checkBox_Sensor.Checked = bool.Parse(tmp[4]);
                textBox_before.Text = tmp[0];//读取保存中的printf提示语句
                textBox_after.Text = tmp[1];//读取保存中的printf提示语句        
                //if (checkBox_Sensor.Checked)
                //{                           
                //TODO 好像printf不存在的变量 m_VariableLocal也不存在
                //又是因为初始化顺序的问题
                if (!comBox_Var.Items.Contains(tmp[2]))
                {
                    //该存储变量在局部变量中不存在 自然也不存在与该下拉选项框中
                    //分别加入这两者
                    Globaldefine.FrmParent.ActivedrmGraphicFlow.m_VariableLocal.Add(tmp[2]);
                    comBox_Var.Items.Add(tmp[2]);
                }
                //无论这个下拉框存不存在（不存在也通过上一步添加进来了） 都要设置成该变量
                comBox_Var.Text = tmp[2];
                comBox_Var.SelectedItem = tmp[2];
                //格式下拉框选项已经提前设定完毕 直接设置当前选中选项即可
                comBox_format.Text = tmp[3];
                comBox_format.SelectedItem = tmp[3];
                //}

            }
            //默认显示
            btn_confirm_Click(new object(), new EventArgs());//触发确认
        }


        /// <summary>
        /// 确认后生成printf对应代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_confirm_Click(object sender, EventArgs e)
        {
            MyIcon.code.Clear();//清空以前代码
            //printf不需要初始化函数
            //MyIcon.code.Initialization = "LCD_Init();    //LCD初始化";
            //设置注释
            MyIcon.code.Comment = "printf" + GetFormat() + printf_data;
            //把四部分（变量前输出字符串+变量格式+变量后输出字符串+变量）组合成printf函数
            if (printf_data != "")
                MyIcon.code.InsertCode = "\tprintf(\"" + printf_tip_before + printf_form + printf_tip_after + "\"," 
                    + printf_data + ");//" + MyIcon.code.Comment;
            else
                MyIcon.code.InsertCode = "\tprintf(\"" + printf_tip_before + printf_form + 
                    printf_tip_after + "\");//" + MyIcon.code.Comment;
            //存储printf参数
            MyIcon.code.Save =printf_tip_before + ";" + printf_tip_after  + ";" + printf_data
                + ";" + printf_form + ";" + checkBox_Sensor.Checked;


            //外部会对此进行判断，因此是必要的
            this.DialogResult = DialogResult.OK;
        }

        private string GetFormat()
        {
            switch (printf_form)
            {
                case "%d":
                    return "以十进制整型输出";
                case "%c":
                    return "以字符型输出";
                case "%f":
                    return "以浮点型输出";
                case "%s":
                    return "以字符串输出";
                default:
                    return "未选择变量格式，无法正确输出";
            }
        }

        /// <summary>
        /// 变量前输出字符串 用户输入后 由printf_tip_before接收
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox_before_TextChanged(object sender, EventArgs e)
        {
            printf_tip_before = textBox_before.Text;
            if (printf_data != "")
                txt_printf.Text = "printf(\"" + printf_tip_before + printf_form + printf_tip_after + "\"," + printf_data + ");";
            else
                txt_printf.Text = "printf(\"" + printf_tip_before + printf_form + printf_tip_after  + "\");";
        }

        /// <summary>
        /// 当用户选择后 修改printf_form的值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comBox_format_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comBox_format.Text != null && comBox_format.Text != "请下拉选择格式" && comBox_format.Text != "")
            {
                printf_form = comBox_format.Text;
                lab_Format_Tip.Text = GetFormat();
            }
            if (printf_data != "")
                txt_printf.Text = "printf(\"" + printf_tip_before + printf_form + printf_tip_after + "\"," + printf_data + ");";
            else
                txt_printf.Text = "printf(\"" + printf_tip_before + printf_form + printf_tip_after + "\");";
        }

        /// <summary>
        /// 变量后输出字符串 用户输入后 由printf_tip_after接收
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox_after_TextChanged(object sender, EventArgs e)
        {
            printf_tip_after = textBox_after.Text;
            if (printf_data != "")
                txt_printf.Text = "printf(\"" + printf_tip_before + printf_form + printf_tip_after + "\"," + printf_data + ");";
            else
                txt_printf.Text = "printf(\"" + printf_tip_before + printf_form + printf_tip_after + "\");";
        }
        /// <summary>
        /// 当用户选择后 修改printf_data的值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comBox_Var_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comBox_Var.Text != null && comBox_Var.Text != "请下拉选择变量")
            {
                printf_data = comBox_Var.Text;
                //传感器模式需要用USB口将数据包含
                if(checkBox_Sensor.Checked && comBox_Var.Text !="")
                {
                    lab_Var_Tip.Text = TransVar(printf_data);
                    if (printf_data.Substring(1, 2).Contains("J"))
                    {
                        textBox_before.Text = printf_data.Substring(1, 2);//取出该变量连的哪一个USB口
                        textBox_after.Text = textBox_before.Text;//头尾都包含
                    }
                    else
                    {
                        MessageBox.Show("该变量是未配置中断的传感器提供的变量！或是非传感器提供的变量！" +
                            "请配置中断或取消传感器模式！");
                    }
                }
            }
            if (printf_data != "")
                txt_printf.Text = "printf(\"" + printf_tip_before + printf_form + printf_tip_after + "\"," + printf_data + ");";
            else
                txt_printf.Text = "printf(\"" + printf_tip_before + printf_form + printf_tip_after + "\");";
        }

        /// <summary>
        /// 翻译变量名 为少儿可以理解的文字
        /// </summary>
        /// <param name="variable"></param>
        private string TransVar(string variable)
        {
            string var_tip = "未选择变量";
            //首字母为b则表示该字符数组传入为变量
            if(variable[0] == 'b')
            {
                var_tip = "该变量存储从";
                //"b" + hardUSB + "_" + MyIcon.info.funs[i].name + match.Value;
                if(variable[1] == 'J')
                {
                    var_tip += variable.Substring(1,2);
                    if (variable.Contains("Temp"))
                        var_tip += "读取的温度传感器数据";
                    else if (variable.Contains("uWave"))
                        var_tip += "读取的超声波传感器数据";
                    else if (variable.Contains("Sound"))
                        var_tip += "读取的声音传感器数据";
                }
            }
            return var_tip;
        }

        /// <summary>
        /// 在文本框被聚焦时，按下按键触发
        /// 主要功能：设置不能输入英文分号';'
        /// </summary>
        private void txt_string_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == ';')
                e.Handled = true;  //表明按键事件已处理
        }

        /// <summary>
        /// 设置comBox_Var中的item选项
        /// </summary>
        private void SetVariables()
        {
            //comBox_Var.Items.Add("");
            if (comBox_Var.Items.Contains(""))
                comBox_Var.Items.Remove("");
            //添加可供选择的系统变量到comBox_Var中
            if (Globaldefine.FrmParent.ActivedrmGraphicFlow != null)
            {
                //传感器对应变量
                foreach (string value in Globaldefine.FrmParent.ActivedrmGraphicFlow.m_Sensor_VariableLocal.Values)
                {
                    if (!comBox_Var.Items.Contains(value))
                        comBox_Var.Items.Add(value);
                }
                //全局变量
                foreach (string value in Globaldefine.FrmParent.ActivedrmGraphicFlow.m_VariableSys)
                {
                    if (!comBox_Var.Items.Contains(value))
                        comBox_Var.Items.Add(value);
                }
                //局部变量
                foreach (string value in Globaldefine.FrmParent.ActivedrmGraphicFlow.m_VariableLocal)
                {
                    if (!comBox_Var.Items.Contains(value))
                        comBox_Var.Items.Add(value);
                }
            }
            comBox_Var.Items.Add("");
        }

        /// <summary>
        /// 当用户下拉时 如果items数量为0 说明用户没有配置终端 给予提示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comBox_Var_DropDown(object sender, EventArgs e)
        {
            if (this.comBox_Var.Items.Count == 0)
            {
                MessageBox.Show("请先点击配置终端！");
            }
        }

        /// <summary>
        /// 点击后弹出使用帮助
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Help_Click(object sender, EventArgs e)
        {
            //新建文本框 布局设置为填充父窗体
            UIRichTextBox textBox = new UIRichTextBox()
            {
                Dock=DockStyle.Fill
            };
            //读取config路径下的printf帮助文档
            string txt=File.ReadAllText(Path.Combine(Application.StartupPath, "Config\\printfHelpDoc.txt"));
            textBox.Text = txt;
            //设置完text后 设置为只读
            textBox.ReadOnly = true;
            //新建窗体放置改文本框 并设置其宽高及显示位置
            Form form = new Form
            {
                Height=800,
                Width=500,
                StartPosition=FormStartPosition.CenterScreen
            };
            form.Controls.Add(textBox);
            form.Show();
        }

        /// <summary>
        /// 窗口关闭时也要保存一下用户输入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmPrintf_FormClosing(object sender, FormClosingEventArgs e)
        {
            btn_confirm_Click(new object(), new EventArgs());//触发确认
        }

    }
}
